package com.example.intelligentattendancesystem.service.impl;

import com.example.intelligentattendancesystem.mapping.HistoryMapping;
import com.example.intelligentattendancesystem.mapping.LeaveMapping;
import com.example.intelligentattendancesystem.mapping.UserMapping;
import com.example.intelligentattendancesystem.mapping.WorkMapping;
import com.example.intelligentattendancesystem.pojo.History;
import com.example.intelligentattendancesystem.pojo.Leave;
import com.example.intelligentattendancesystem.pojo.User;
import com.example.intelligentattendancesystem.pojo.Work;
import com.example.intelligentattendancesystem.service.SignService;
import com.example.intelligentattendancesystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author
 * @version 1.0
 * @className SignServiceImpl
 * @since 1.0
 */
@Service
public class SignServiceImpl implements SignService {
    @Autowired
    UserMapping userMapping;
    @Autowired
    WorkMapping workMapping;
    @Autowired
    HistoryMapping historyMapping;
    @Autowired
    Work work;
    @Autowired
    LeaveMapping leaveMapping;
    @Autowired
    LateServiceImpl lateService;
    @Autowired
    UserService userService;

    @Override
    public List<User> getNoSignUserService(String workTime) {
        List<History> sucAttUser = getSucAttUser(workTime);
        List<Integer> sucIds = new ArrayList<>();
        for (History his :
                sucAttUser) {
            sucIds.add(his.getUserId());
        }
        List<Integer> needIds = getNeedActUsers(workTime);
        List<Integer> userIds = new ArrayList<>();

        int flag=0;
        for (Integer needId :needIds) {
            flag=0;
            for (Integer sucId :sucIds) {
                if (needId==sucId){
                    flag=1;
                    break;
                }
            }
            if (flag==0){
                userIds.add(needId);
            }
        }
        List<User> users = userService.getUsersService(userIds);
        return users;
    }

    @Override
    public List<User> getLateUserService(String currentTime ,String week, String startTime, String preEndTime) {
        //先查询该时刻表的所有员工id
        Work work1 = new Work();
        work1.setStartTime(startTime);
        work1.setWeek(week);
        List<Integer> userIds = workMapping.selectUserIdByWork(work1);
        //今天的字符串拼接
        String today=currentTime.split(" ")[0];
        //通过所有员工id查询员工在今天的打卡记录,移除成功打卡的员工
        for (int i = 0; i < userIds.size(); i++) {
            List<History> histories = historyMapping.selectHistoryByUserIdInToday(userIds.get(i),today);
            for (int j = 0; j < histories.size(); j++) {
                if(histories.get(j).getSignInTime().compareTo(today+" "+startTime)<0&&histories.get(j).getSignInTime().compareTo(today+" "+preEndTime)>0){
                    userIds.remove(i);
                }
            }
        }
        //移除未打卡的员工
        List<User> noSignUsers = getNoSignUserService(currentTime);
        System.out.println(noSignUsers);
        for (int i = 0; i < noSignUsers.size(); i++) {
            for (int j = 0; j < userIds.size(); j++) {
                if(userIds.get(j)==noSignUsers.get(i).getUserId()){
                    userIds.remove(j);
                }
            }
        }
        List<User> users = new ArrayList<>();
        //查询未打卡的员工
        for (int i = 0; i < userIds.size(); i++) {
            User user = userMapping.selectUserByUserId(userIds.get(i));
            users.add(user);
        }
        return users;
    }

    @Override
    public boolean clockInService( int userId, String position, String currentTime, String endTime, String startTime, String week) {
        //打卡记录的保存
        String signPosition=position;
        System.out.println(signPosition);
        String signOutTime=currentTime.split(" ")[0]+" "+endTime;
        String signInTime=currentTime;
        History history = new History(null, userId, signInTime, signOutTime, signPosition);
        //判断是否有相同的打卡记录
        List<History> histories = historyMapping.selectHistoryByUserIdInToday(userId, currentTime.split(" ")[0]);
        for (int i = 0; i < histories.size(); i++) {
            if(histories.get(i).getUserId()==history.getUserId() && histories.get(i).getSignOutTime().equals(history.getSignOutTime()) ){
                return false;
            }
        }
        //判断是否已经请假啦
        int i=0;
        List<Leave> leaves = leaveMapping.selectLeaveByUserId(userId);
        for (Leave leave:leaves) {
            if (leave.getLeaveEndTime().equals(signOutTime)) {
                return false;
            }
        }
        //没有请假，没有重复
        i = historyMapping.insertHistory(history);

        //判断是否迟到
        System.out.println(currentTime.compareTo(currentTime.split(" ")[0]+" "+startTime));

        if(currentTime.compareTo(currentTime.split(" ")[0]+" "+startTime)>0){
            lateService.addLateService(userId, currentTime);
        }

//        System.out.println("didian:"+history.getSignPosition());
        if(i>0)
            return true;
        return false;
    }

    @Override
    public List<History> getSignRecord(String currentTime, int userId) {
        List<History> histories = historyMapping.selectHistoryByUserId(userId);
        List<History> histories1 = new ArrayList<>();
        //将本月记录找出来
        String curDay = currentTime.split(" ")[0];
        //月份，找preDay-curDay的记录
        String preDay = curDay.split("-")[0]+"-"+curDay.split("-")[1]+"-00";
        System.out.println(preDay+"--"+curDay);
        for (int i = 0; i < histories.size(); i++) {
            if(histories.get(i).getSignInTime().split(" ")[0].compareTo(curDay)<=0 && histories.get(i).getSignInTime().split(" ")[0].compareTo(preDay)>=0){
                histories1.add(histories.get(i));
            }
        }
        return histories1;
    }

    @Override
    public List<History> getSucAttUser(String workTime) {
        String start = workTime.split("-")[0];
        String end = workTime.split("-")[1];
        Date date = new Date();
        String time = new SimpleDateFormat("YYYY-MM-dd").format(date);
        start = time+" "+start+":00";
        end = time+" "+end+":00";
        List<History> histories = historyMapping.selectAllHistory();
        List<History> histories2 = new ArrayList<>();
        //只能在前十分钟打卡该课程，所以只需要签退的时间与该课程结束时间相同，就是当前已经打卡的员工
        for (History history :
                histories) {
            if(history.getSignOutTime().equals(end)){
                histories2.add(history);
            }
        }
        System.out.println(histories2);
        //获取这些员工的id
        return histories2;
    }

    @Override
    public List<Integer> getNeedActUsers(String workTime) {
        if(workTime==null||workTime.equals("")||workTime.split("-").length!=2){
            return null;
        }
        String end = workTime.split("-")[1];
        Date date = new Date();
        end = end+":00";
        //获取星期
        int day = date.getDay();
        String week = day+"";
        //查询所有工作表
        List<Work> works = workMapping.selectAllWork();
        List<Integer> userIds = new ArrayList<>();
        for (Work work: works) {
            //如果星期一样，班次结束时间相同，即定位到该班，就把该班的用户id取出来
            if(week.equals(work.getWeek())&&end.equals(work.getEndTime())){
                userIds.add(work.getUserId());
            }
        }
        return userIds;
    }

}
